import { create } from 'zustand'

interface FamilyMember {
  id: number
  name: string
  gender: 'MALE' | 'FEMALE'
  birthDate?: string
  deathDate?: string
  isAlive: boolean
  avatar?: string
  bio?: string
  parentId?: number
  spouseId?: number
  generation: number
  createdAt: string
  updatedAt: string
  parent?: FamilyMember
  children?: FamilyMember[]
  spouse?: FamilyMember
}

interface FamilyTree {
  id: number
  name: string
  description?: string
  rootMemberId: number
  createdBy: number
  createdAt: string
  updatedAt: string
  rootMember?: FamilyMember
  members?: FamilyMember[]
}

interface TreeNode {
  id: number
  name: string
  gender: string
  avatar?: string
  generation: number
  level: number
  spouse?: {
    id: number
    name: string
    gender: string
    avatar?: string
  }
  children: TreeNode[]
}

interface TreeStructure {
  id: number
  name: string
  description?: string
  structure: TreeNode | null
}

interface FamilyStore {
  members: FamilyMember[]
  trees: FamilyTree[]
  currentTree: FamilyTree | null
  treeStructure: TreeStructure | null
  loading: boolean
  error: string | null
  
  // Actions
  fetchMembers: () => Promise<void>
  fetchTrees: () => Promise<void>
  fetchTree: (id: number) => Promise<void>
  fetchTreeStructure: (id: number) => Promise<void>
  createMember: (member: Partial<FamilyMember>) => Promise<void>
  updateMember: (id: number, member: Partial<FamilyMember>) => Promise<void>
  deleteMember: (id: number) => Promise<void>
  createTree: (tree: Partial<FamilyTree>) => Promise<void>
  updateTree: (id: number, tree: Partial<FamilyTree>) => Promise<void>
  deleteTree: (id: number) => Promise<void>
  setCurrentTree: (tree: FamilyTree | null) => void
}

export const useFamilyStore = create<FamilyStore>((set, get) => ({
  members: [],
  trees: [],
  currentTree: null,
  treeStructure: null,
  loading: false,
  error: null,

  fetchMembers: async () => {
    set({ loading: true, error: null })
    try {
      const response = await fetch('/api/family/members')
      const data = await response.json()
      if (data.success) {
        set({ members: data.data.data || [] })
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  fetchTrees: async () => {
    set({ loading: true, error: null })
    try {
      const response = await fetch('/api/family/trees')
      const data = await response.json()
      if (data.success) {
        set({ trees: data.data.data || [] })
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  fetchTree: async (id: number) => {
    set({ loading: true, error: null })
    try {
      const response = await fetch(`/api/family/trees/${id}`)
      const data = await response.json()
      if (data.success) {
        set({ currentTree: data.data })
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  fetchTreeStructure: async (id: number) => {
    set({ loading: true, error: null })
    try {
      const response = await fetch(`/api/family/trees/${id}/structure`)
      const data = await response.json()
      if (data.success) {
        set({ treeStructure: data.data })
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  createMember: async (member) => {
    set({ loading: true, error: null })
    try {
      const response = await fetch('/api/family/members', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(member),
      })
      const data = await response.json()
      if (data.success) {
        await get().fetchMembers()
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  updateMember: async (id, member) => {
    set({ loading: true, error: null })
    try {
      const response = await fetch(`/api/family/members/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(member),
      })
      const data = await response.json()
      if (data.success) {
        await get().fetchMembers()
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  deleteMember: async (id) => {
    set({ loading: true, error: null })
    try {
      const response = await fetch(`/api/family/members/${id}`, {
        method: 'DELETE',
      })
      const data = await response.json()
      if (data.success) {
        await get().fetchMembers()
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  createTree: async (tree) => {
    set({ loading: true, error: null })
    try {
      const response = await fetch('/api/family/trees', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(tree),
      })
      const data = await response.json()
      if (data.success) {
        await get().fetchTrees()
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  updateTree: async (id, tree) => {
    set({ loading: true, error: null })
    try {
      const response = await fetch(`/api/family/trees/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(tree),
      })
      const data = await response.json()
      if (data.success) {
        await get().fetchTrees()
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  deleteTree: async (id) => {
    set({ loading: true, error: null })
    try {
      const response = await fetch(`/api/family/trees/${id}`, {
        method: 'DELETE',
      })
      const data = await response.json()
      if (data.success) {
        await get().fetchTrees()
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  setCurrentTree: (tree) => {
    set({ currentTree: tree })
  },
}))